package utils;

import book.Book;
import book.PariOfUidAndBookId;
import com.bit.utils.FileUtils;

import java.io.IOException;
import java.time.LocalDate;

public class AnalyzingBorrowBook {

    //将指定的书籍信息内容存放指定文件
    //将书籍信息存放到指定文件中
    public void storeBook(PariOfUidAndBookId[] pariOfUidAndBookIds, String fileName)  {
        int useBookLength = 0;
        //统计实际使用的空间
        for (int i = 0; i < pariOfUidAndBookIds.length; i++) {
            if(pariOfUidAndBookIds[i] != null) useBookLength++;
        }
        //拼接
        StringBuilder toJson =new StringBuilder();
        for (int i = 0; i < useBookLength; i++) {
            if(pariOfUidAndBookIds[i] != null){
                toJson.append(pariOfUidAndBookIds[i].toJon());
            }
            if(i != useBookLength - 1) toJson.append("\n");
        }
        //写入指定文件
        FileUtils.writeFile(toJson.toString(),fileName);
    }
    //从指定文件中读取书籍信息
    public PariOfUidAndBookId[] loadObject(String fileName){
        //1,从文件中读取内容
        String context = FileUtils.readFile(Constant.BORROWED_BOOK_FILE_NAME);
        if(context == null || context.isEmpty())
        {
            System.out.println("文件为空或者引用为空不可读取:" + fileName);
            return null;
        }
        //2.分割
        String[] booklist = context.split("\n");
        //3.将字符串组成书籍对象
        PariOfUidAndBookId[] pariOfUidAndBookIds = new PariOfUidAndBookId[booklist.length];
        for (int i = 0; i < pariOfUidAndBookIds.length;i++) {

           PariOfUidAndBookId pariOfUidAndBookId = new PariOfUidAndBookId();

           String[] UserIDandBookId = booklist[i].split(",");

           pariOfUidAndBookId.setUserId(Integer.parseInt(UserIDandBookId[0]));
            pariOfUidAndBookId.setBookId(Integer.parseInt(UserIDandBookId[1]));

            pariOfUidAndBookIds[i] = pariOfUidAndBookId;

        }
        return pariOfUidAndBookIds;
    }
    //序列号书籍信息
    private PariOfUidAndBookId parseBookJson(String json){
        //1,判断
        if(json == null || json.isEmpty()){
            System.out.println("引用为空！！！");
            return null;
        }
        //2，分割
        String[] pairs = json.split(",");
        //3.赋值临时变量
        int UserId = Integer.parseInt(pairs[0]);
        int BookId = Integer.parseInt(pairs[1]);
        //4.赋值对象
        PariOfUidAndBookId pariOfUidAndBookId = new PariOfUidAndBookId(UserId,BookId);
        //5.返回
        return pariOfUidAndBookId;
    }
    public static void main1(String[] args) {
        PariOfUidAndBookId[] pariOfUidAndBookId = new PariOfUidAndBookId[2];
        pariOfUidAndBookId[0] = new PariOfUidAndBookId(1001,1);
        pariOfUidAndBookId[1] = new PariOfUidAndBookId(123,2);

        AnalyzingBorrowBook analyzingBorrowBook = new AnalyzingBorrowBook();
        analyzingBorrowBook.storeBook(pariOfUidAndBookId,Constant.BORROWED_BOOK_FILE_NAME);
    }
}
